package cn.itcast.service.impl;

import cn.itcast.dao.AccountDao;
import cn.itcast.domain.Account;
import cn.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    @Autowired
    private RedisTemplate<String,List<Account>> redisTemplate;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Account> findAll() throws Exception {
        List<Account> accounts = redisTemplate.opsForValue().get("accounts");
        if (accounts == null){
            List<Account> list = accountDao.findAll();
            redisTemplate.opsForValue().set("accounts",list);
            System.out.println("从mysql中拿数据");
            return list;
        }else {
            System.out.println("从redis中拿数据");
            return accounts;
        }

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Account findById(Integer id) throws Exception {
        return accountDao.findById(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void update(Account account) throws Exception {
        accountDao.update(account);
        redisTemplate.delete("accounts");
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void delete(Integer id) throws Exception {
        accountDao.delete(id);
        redisTemplate.delete("accounts");

    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void add(Account account) throws Exception {
        accountDao.add(account);
        redisTemplate.delete("accounts");

    }
}
